package com.example.dao;

import com.example.bean.Notice;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NoticeDAO {
    public boolean publishNotice(Notice notice) {
        String sql = "INSERT INTO notices (title, content, publish_time, publisher) VALUES (?, ?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, notice.getTitle());
            pstmt.setString(2, notice.getContent());
            pstmt.setTimestamp(3, new java.sql.Timestamp(notice.getPublishTime().getTime()));
            pstmt.setString(4, notice.getPublisher());
            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            System.err.println("发布公告时发生 SQL 异常: " + e.getMessage());
            return false;
        }
    }
    public List<Notice> getAllNotices() {
        List<Notice> noticeList = new ArrayList<>();
        String sql = "SELECT * FROM notices ORDER BY publish_time DESC";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                Notice notice = new Notice();
                notice.setId(rs.getInt("id"));
                notice.setTitle(rs.getString("title"));
                notice.setContent(rs.getString("content"));
                notice.setPublishTime(rs.getTimestamp("publish_time"));
                notice.setPublisher(rs.getString("publisher"));
                noticeList.add(notice);
            }
        } catch (SQLException e) {
            System.err.println("获取公告列表时发生 SQL 异常: " + e.getMessage());
        }
        return noticeList;
    }
}